package com.lujieni.msg.consumer.service;

import com.alibaba.fastjson.JSONObject;
import com.lujieni.msg.common.properties.rabbitmq.RabbitMqQueueMapProperties;
import com.lujieni.msg.consumer.dao.LocalEventProcessDao;
import com.lujieni.msg.consumer.dao.StudentDao;
import com.lujieni.msg.consumer.po.LocalEventProcessPO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;

/**
 * @author lujieni
 * @Title: LocalEventQueueReceiver
 * @Description: 下游执行本地事件
 * @date 2025/01/30 19:56 下午
 */
@Service
@Slf4j
public class LocalEventQueueReceiver {

    @Autowired
    private LocalEventProcessDao localEventProcessDao;

    @RabbitListener(queues = "local.event.queue") //绑定的是Queue类型的对象
    public void receiveLocalEventQueue(Message message, Channel channel) throws IOException {
        LocalEventProcessPO localEventProcessPO = JSONObject.parseObject(new String(message.getBody()), LocalEventProcessPO.class);
        log.info("receiveLocalEventQueue 接收消息:{}", localEventProcessPO);
        if(localEventProcessPO.getId() == null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        // 判断是否重复消息
        if(localEventProcessDao.selectByPrimaryKey(localEventProcessPO.getId()) != null){
            // 重复消息自己ack掉
            log.error("receiveLocalEventQueue 重复消息:{}", localEventProcessPO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        try {
            localEventProcessPO.setStatus(0); //待处理
            localEventProcessDao.insert(localEventProcessPO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("receiveLocalEventQueue error", e);
            // 如果数据库挂了这里会进入异常
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); //false: 发往死信或者丢失 true:回退队列,继续消费
        }
    }

}
